package com.lzxuni.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

public class ImageWatermarking {

    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     * @param logoText 要写入的文字
     * @param srcImgPath 源图片路径
     * @param newImagePath 新图片路径
     * @param degree 旋转角度
     * @param color  字体颜色
     * @param formaName 图片后缀
     */
    public static void markImageByText(String logoText, String srcImgPath,String newImagePath,Integer degree,Color color,String formaName,String timet) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 源图片
            java.awt.Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg =new BufferedImage(srcImg.getWidth(null),srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            //  g.drawImage
            g.drawImage(srcImg, 0, 0, null);

            // 设置矩形图片颜色
            int imgHeight = srcImg.getHeight(null);
            /*if(imgHeight < 200){
                *//*Font font = new Font("04b_08", Font.PLAIN,imgHeight / 100 * 10);*//*
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /100*11));
            }else{
                *//*Font font = new Font("04b_08", Font.PLAIN,imgHeight / 200 * 10);*//*
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /200*10));
            }*/
            if(imgHeight <= 50){
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /15*5));
            }else if(imgHeight <= 100){
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /25*5));
            }else if(imgHeight < 200){
                /*Font font = new Font("04b_08", Font.PLAIN,imgHeight / 100 * 10);*/
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /100*11));
            }else{
                /*Font font = new Font("04b_08", Font.PLAIN,imgHeight / 200 * 10);*/
                g.setFont(new java.awt.Font("04b_08", Font.PLAIN,buffImg.getHeight() /200*10));
            }
            /*g.setFont(new java.awt.Font("宋体", java.awt.Font.BOLD,buffImg.getWidth() /200*6));*/
            // 设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));

            int fontlen = getWatermarkLength(logoText, g);

            int line = fontlen/buffImg.getWidth() ;//文字长度相对于图片宽度应该有多少行

            g.setColor(new Color(128, 128, 128));
            g.setStroke(new BasicStroke(1f));
            //line +  3   调整文字背景颜色高度
            /*g.fillRect(0, buffImg.getHeight()  - (line+3)*(buffImg.getWidth() /100*5), srcImg.getWidth(null), srcImg.getHeight(null));*/
            if(imgHeight < 1000){
                g.fillRect(0, buffImg.getHeight()  - (line+4)*(buffImg.getWidth() /100*5), srcImg.getWidth(null), srcImg.getHeight(null));
            }else{
                g.fillRect(0, buffImg.getHeight()  - (line+3)*(buffImg.getWidth() /100*5), srcImg.getWidth(null), srcImg.getHeight(null));
            }

            //画完矩形背景后重新设置水印颜色
            g.setColor(color);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));

            int y = buffImg.getHeight()  - (line + 1)*(buffImg.getHeight() /100*5);

            //文字叠加,自动换行叠加
            int tempX = 10;
            int tempY = y;
            int tempCharLen = 0;//单字符长度
            int tempLineLen = 0;//单行字符总长度临时计算
            StringBuffer sb =new StringBuffer();
            for(int i=0; i<logoText.length(); i++) {
                char tempChar = logoText.charAt(i);
                tempCharLen = getCharLen(tempChar, g);

                tempLineLen += tempCharLen;

                if(tempLineLen >= buffImg.getWidth()) {
                    //长度已经满一行,进行文字叠加
                    g.drawString(sb.toString(), tempX, tempY);

                    sb.delete(0, sb.length());//清空内容,重新追加

                    tempY += (buffImg.getHeight() /100*5);

                    tempLineLen =0;
                }
                sb.append(tempChar);//追加字符
            }

            g.drawString(sb.toString(),  10 , buffImg.getHeight()-buffImg.getHeight() /100*4);

            /*int name = buffImg.getHeight()  - (line+3)*(buffImg.getWidth() /300*15);

            String s_name="应歧林";
            StringBuffer sb2 =new StringBuffer();
            for(int i=0; i<s_name.length(); i++) {
            	  char tempChar = s_name.charAt(i);
            	  sb2.append(tempChar);//追加字符
            }
            g.drawString(sb2.toString(),  0 ,name);*/

            /*int time = buffImg.getHeight()  - (line+2)*(buffImg.getWidth() /100*5);*/
            int time = buffImg.getHeight()  - (line+2)*(buffImg.getHeight() /100*5);


            StringBuffer sb3 =new StringBuffer();
            for(int i=0; i<timet.length(); i++) {
                char tempChar = timet.charAt(i);
                sb3.append(tempChar);//追加字符
            }

            // 第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(sb3.toString(),  10 ,time-10);

            // 释放资源
            g.dispose();
            // 生成图片
            os = new FileOutputStream(newImagePath);
            ImageIO.write(buffImg, formaName, os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取水印文字总长度
     *@paramwaterMarkContent水印的文字
     *@paramg
     *@return水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),0, waterMarkContent.length());
    }

    public static int getCharLen(char c, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charWidth(c);
    }



    /**
     * 绘制图形，把自己绘制的图形设置为透明或半透明，背景并不透明   前景透明，背景依然是黑色
     * @throws IOException
     */
    public static void drawImage1() throws IOException {
        int width=256;
        int height=256;
        //创建BufferedImage对象
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取Graphics2D
        Graphics2D g2d = bi.createGraphics();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.2f));// 1.0f为透明度 ，值从0-1.0，依次变得不透明

        // 画图BasicStroke是JDK中提供的一个基本的画笔类,我们对他设置画笔的粗细，就可以在drawPanel上任意画出自己想要的图形了。
        g2d.setColor(new Color(128, 128, 128));
        g2d.setStroke(new BasicStroke(1f));
        g2d.fillRect(128, 128, width, height);

        // 释放对象 透明度设置结束
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
        g2d.dispose();

        // 保存文件
        /*ImageIO.write(bi, "png", new File("C:/yql/test.png"));*/
    }

    /**
     * 绘制透明图形
     * @throws IOException
     */
    public static void drawTransparent() throws IOException{
        int width=256;
        int height=256;
        //创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取Graphics2D
        Graphics2D g2d = image.createGraphics();

        // 增加下面代码使得背景透明
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        // 背景透明代码结束

        // 画图BasicStroke是JDK中提供的一个基本的画笔类,我们对他设置画笔的粗细，就可以在drawPanel上任意画出自己想要的图形了。
        g2d.setColor(new Color(255, 0, 0));
        g2d.setStroke(new BasicStroke(1f));
        g2d.fillRect(128, 128, width, height);

        // 释放对象
        g2d.dispose();

        // 保存文件
        /*ImageIO.write(image, "png", new File("C:/yql/test.png"));*/
    }
}
